package com.cmcc.waf.report.core;

import com.cmcc.waf.report.core.exception.BusinessException;
import com.cmcc.waf.report.core.exception.ErrorCode;
import com.cmcc.waf.report.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 全局异常处理
 *
 * @author liang_jinxin
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 统一参数校验异常处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Object> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        // 获取所有异常
        List<String> errors = e.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(item -> item.getField() + item.getDefaultMessage())
                .collect(Collectors.toList());
        return new Result<>().error(String.join(",", errors));
    }

    /**
     * 处理HttpRequestMethodNotSupportedException
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<Object> handlerHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        return new Result().error(ErrorCode.REQUEST_METHOD_ERROR);
    }

    /**
     * org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'playbackInterface' is not present
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result<Object> handlerMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        return new Result().error(e.getParameterName() + "参数不能为空");
    }

    /**
     * 处理BusinessException
     */
    @ExceptionHandler(BusinessException.class)
    public Result<Object> handlerBusinessException(BusinessException be) {
        return new Result().error(be.getCode(), be.getMsg());
    }




    /**
     * 处理未知异常
     */
    @ExceptionHandler(Exception.class)
    public Result<Object> handlerException(Exception e) {
        log.error("handler Global Exception: ", e);
        return new Result<>().error("未知异常，请联系管理员!");
    }

}
